<template>
  <div class="utilization">
    <div class="utilization-header">
      <span>集群利用率</span>
    </div>

    <!-- 添加弹窗 -->
    <el-dialog
      :visible.sync="dialogVisible"
      :title="dialogTitle"
      :before-close="handleDialogClose"
      :close-on-click-modal="false"
      width="520px">
      <add-utilization
        v-if="dialogType === 'add'"
        :type="utilizationType"
        :nodeData="NodeUtilization"
        :rscData="ResUtilization"
        @close="handleDialogClose"
        @success="handleAddSuccess">
      </add-utilization>
    </el-dialog>

    <!-- 表格内容 -->
    <div class="utilization-content" v-loading="utilizeLoading">
      <el-tabs v-model="activeName">
        <!-- 节点利用率 -->
        <el-tab-pane label="节点" name="node">
          <el-table
            :data="NodeUtilization"
            :header-cell-style="{
              'background-color': '#eceef0',
              'border-top': '4px solid #44b1ff',
              'border-bottom': '2px solid #dedede',
              height: '50px',
              color: '#222',
            }">
            <el-table-column prop="name" label="节点" min-width="150"></el-table-column>
            <el-table-column prop="attri" label="属性名" min-width="150"></el-table-column>
            <el-table-column prop="value" label="值" min-width="150">
              <template slot-scope="{ row }">
                <div v-if="row.isEdit">
                  <el-input v-model="row.editValue" @input="handleAttrValueChange(row)" size="small"></el-input>
                  <div v-if="row.isError" class="error-tip">输入大于等于0的整数！</div>
                </div>
                <span v-else>{{ row.value }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="250">
              <template slot="header">
                <el-button type="primary" size="small" @click="handleAdd('node')">添加</el-button>
              </template>
              <template slot-scope="{ row }">
                <el-popconfirm
                  title="是否确认删除此利用率属性?"
                  confirm-button-text="确认"
                  cancel-button-text="取消"
                  @confirm="handleDelete(row, 'node')">
                  <el-button slot="reference" type="text" style="color: #f56c6c;">删除</el-button>
                </el-popconfirm>
                <el-button v-if="!row.isEdit" type="text" @click="handleEditFlag(row, 'edit')">编辑</el-button>
                <el-button v-if="row.isEdit" type="text" @click="handleEditConfirm(row, 'node')">保存</el-button>
                <el-button v-if="row.isEdit" type="text" @click="handleEditFlag(row, 'cancel')">取消</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 资源利用率 -->
        <el-tab-pane label="资源" name="resource">
          <el-table
            :data="ResUtilization"
            :header-cell-style="{
              'background-color': '#eceef0',
              'border-top': '4px solid #44b1ff',
              'border-bottom': '2px solid #dedede',
              height: '50px',
              color: '#222',
            }">
            <el-table-column prop="name" label="资源" min-width="150"></el-table-column>
            <el-table-column prop="attri" label="属性名" min-width="150"></el-table-column>
            <el-table-column prop="value" label="值" min-width="150">
              <template slot-scope="{ row }">
                <div v-if="row.isEdit">
                  <el-input v-model="row.editValue" @input="handleAttrValueChange(row)" size="small"></el-input>
                  <div v-if="row.isError" class="error-tip">输入大于等于0的整数！</div>
                </div>
                <span v-else>{{ row.value }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="250">
              <template slot="header">
                <el-button type="primary" size="small" @click="handleAdd('resource')">添加</el-button>
              </template>
              <template slot-scope="{ row }">
                <el-popconfirm
                  title="是否确认删除此利用率属性?"
                  confirm-button-text="确认"
                  cancel-button-text="取消"
                  @confirm="handleDelete(row, 'resource')">
                  <el-button slot="reference" type="text" style="color: #f56c6c;">删除</el-button>
                </el-popconfirm>
                <el-button v-if="!row.isEdit" type="text" @click="handleEditFlag(row, 'edit')">编辑</el-button>
                <el-button v-if="row.isEdit" type="text" @click="handleEditConfirm(row, 'resource')">保存</el-button>
                <el-button v-if="row.isEdit" type="text" @click="handleEditFlag(row, 'cancel')">取消</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { addOrEditUtilization, delUtilization } from '@/api/advanced'
import AddUtilization from './form/AddUtilization.vue'

export default {
  name: 'Utilization',
  components: {
    AddUtilization
  },
  data() {
    return {
      activeName: 'node',
      dialogVisible: false,
      dialogTitle: '',
      dialogType: '',
      utilizationType: ''
    }
  },
  computed: Object.assign(
    {},
    mapGetters('advanced', ['utilizeLoading', 'NodeUtilization', 'ResUtilization']),
    mapGetters('cluster', ['clusterName'])
  ),
  mounted() {
    this.fetchData()
  },
  watch: {
    // 监听集群名称变化
    clusterName: function(newVal, oldVal) {
      if (newVal && oldVal && newVal !== oldVal) {
        console.log('集群切换，刷新集群利用率数据:', newVal)
        this.fetchData()
      }
    }
  },
  methods: {
    // 获取数据
    fetchData() {
      this.$store.dispatch('advanced/fetchUtilizationData').catch(error => {
        this.$message.error(error || '获取利用率数据失败')
      })
    },
    // 添加
    handleAdd(type) {
      this.dialogVisible = true
      this.dialogType = 'add'
      this.dialogTitle = type === 'node' ? '添加节点利用率' : '添加资源利用率'
      this.utilizationType = type
    },
    // 弹窗关闭
    handleDialogClose() {
      this.dialogVisible = false
      this.dialogType = ''
      this.dialogTitle = ''
      this.utilizationType = ''
    },
    // 添加成功
    handleAddSuccess() {
      this.handleDialogClose()
      this.fetchData()
    },
    // 编辑标识
    handleEditFlag(row, type) {
      if (type === 'cancel') {
        row.isEdit = false
        row.isError = false
        row.editValue = row.value
      } else {
        row.isEdit = true
      }
    },
    // 校验编辑的属性值
    handleAttrValueChange(row) {
      const reg = /^([1-9]\d*|[0]{1,1})$/
      row.isError = !reg.test(row.editValue)
    },
    // 编辑确认
    handleEditConfirm(row, type) {
      const self = this
      if (row.isError) {
        this.$message.error('请输入正确的值')
        return
      }

      const data = {
        name: row.name,
        type: type
      }
      data[row.attri] = row.editValue

      addOrEditUtilization(data).then(function(res) {
        if (res.data.action) {
          self.$message.success(res.data.info || '编辑成功')
          self.fetchData()
        } else {
          self.$message.error(res.data.error || '编辑失败')
        }
      }).catch(function() {
        self.$message.error('编辑失败')
      })
    },
    // 删除
    handleDelete(row, type) {
      const self = this
      const data = {
        name: row.name,
        type: type
      }
      data[row.attri] = row.value

      delUtilization(data).then(function(res) {
        if (res.data.action) {
          self.$message.success(res.data.info || '删除成功')
          self.fetchData()
        } else {
          self.$message.error(res.data.error || '删除失败')
        }
      }).catch(function() {
        self.$message.error('删除失败')
      })
    }
  }
}
</script>

<style scoped>
.utilization-header {
  height: 60px;
  line-height: 60px;
  background: #f6f8fd;
  border-bottom: 2px solid #e4eaf9;
  padding: 0 20px;
  font-size: 16px;
  font-weight: bold;
}

.utilization-content {
  margin: 20px;
}

.error-tip {
  color: #f56c6c;
  font-size: 12px;
  line-height: 1;
  padding-top: 4px;
}
</style>
